package com.fancy.application.sys.org.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.fancy.application.common.service.impl.BaseService;
import com.fancy.application.sys.org.entity.SysOrgDept;
import com.fancy.application.sys.org.entity.SysOrgElement;
import com.fancy.application.sys.org.entity.SysOrgModel;
import com.fancy.application.sys.org.mapper.SysOrgDeptMapper;
import com.fancy.application.sys.org.service.ISysOrgDeptService;
import com.fancy.application.sys.org.service.ISysOrgElementService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
* fancycode自动生成v1.0
* @author wison
* 2019-09-07
*/
@Service("sysOrgDeptService")
public class SysOrgDeptServiceImpl extends BaseService<SysOrgDeptMapper,SysOrgDept> implements ISysOrgDeptService {
    @Resource
    private ISysOrgElementService sysOrgElementService;
    @Override
    public void saveOrUpdateDept(SysOrgDept sysOrgDept) {
        if(StrUtil.isNotEmpty(sysOrgDept.getFdParentId())){
            SysOrgDept parentDept = this.getById(sysOrgDept.getFdParentId());
            if(parentDept == null){
                SysOrgElement element = sysOrgElementService.getById(sysOrgDept.getFdParentId());
                sysOrgDept.setFdParentOrgId(element.getFdId());
                sysOrgDept.setFdParentOrgName(element.getFdName());
            }else{
                sysOrgDept.setFdParentOrgId(parentDept.getFdParentOrgId());
                sysOrgDept.setFdParentOrgName(parentDept.getFdParentOrgName());
            }
        }
        this.saveOrUpdate(sysOrgDept);
    }

    @Override
    public boolean saveOrUpdate(SysOrgDept sysOrgDept){
        String fdParentId = sysOrgDept.getFdParentId();
        if(StrUtil.isEmpty(sysOrgDept.getFdId())){
            sysOrgDept.setFdId(IdUtil.simpleUUID());
        }
        String fdHierarchyId = "";
        if(StrUtil.isNotEmpty(fdParentId)) {
            SysOrgModel model = this.getById(fdParentId);
            if(model == null){
                model = sysOrgElementService.getById(fdParentId);
            }
            fdHierarchyId = model.getFdHierarchyId();
        }
        if(StrUtil.isEmpty(fdHierarchyId)){
            fdHierarchyId += sysOrgDept.getFdId();
        }else{
            fdHierarchyId = fdHierarchyId+"x"+sysOrgDept.getFdId();
        }
        sysOrgDept.setFdHierarchyId(fdHierarchyId);
        return super.saveOrUpdate(sysOrgDept);
    }
}
